/*
 * @LastEditors: yuSeen
 * @LastEditTime: 2022-01-11 12:30:59
 * 天凉好个秋
 */
import type { IAllObject, allArray } from "@/types/base";

/**
 * @description: 根据文件路径获取文件名
 * @param {string} filePath
 * @return {string} string
 */
export const getFileName = (filePath: string): string => {
  return filePath.split("/").pop()?.slice(0, -3) as string;
};

/**
 * @description: 将批量导入的模块以键值对的形式存储到一个对象上
 * @param {Record} modules
 * @return {IAllObject}
 */
export const batchImportAsObj = (
  modules: Record<string, IAllObject>
): IAllObject => {
  const result: { [propName: string]: any } = {};
  Object.keys(modules).forEach((key) => {
    const fileName = getFileName(key);
    result[fileName] = modules[key].default;
  });
  return result;
};

/**
 * @description: 将批量导入的模块以键值对的形式存储到一个数组上
 * @param {Record} modules
 * @return {IAllObject}
 */
export const batchImportAsArr = (
  modules: Record<string, IAllObject>
): allArray => {
  const result: allArray = [];
  Object.keys(modules).forEach((key) => {
    result.push(modules[key].default);
  });
  return result;
};

// 从复杂的cookie中提取主要部分，用于身份验证
export const getSimpleCookie = (cookie: string): string => {
  if (!cookie) return '';
  let cookieArr = cookie.split(";");
  let obj: { [propName: string]: any } = {};
  cookieArr.forEach((i) => {
    let arr = i.split("=");
    obj[arr[0]] = arr[1];
  });
//   关键字段
  const mainKeyword = ['MUSIC_U', '__csrf', 'NMTID' ]
  let res = ''
  for(let key of mainKeyword) {
      res += `${key}=${obj[key]}; `
  }
  return res;
};

// 给值较大的数加上合适的单位以减少长度
export const numberAddUnit = (num: number) => {
    if(num < 100000) return num
    if(num < 100000000) return Math.floor(num / 10000) + '万'
    return Math.floor(num / 100000000) + '亿'
}

// 判断对象是否为空
export const notEmptyObj = (obj: IAllObject): boolean => {
  if(typeof obj !== 'object') return false
  if(Object.keys(obj).length) return true
  return false
}

// 解ref
export const unref = <T = any>(source: any) => {
  return (source?.current ? source.current : source) as T
}
